package com.guoliang.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guoliang.eduService.entity.EduChapter;
import com.guoliang.eduService.entity.EduVideo;
import com.guoliang.eduService.entity.vo.ChapterVo;
import com.guoliang.eduService.entity.vo.VideoVo;
import com.guoliang.eduService.mapper.EduChapterMapper;
import com.guoliang.eduService.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guoliang.eduService.service.EduVideoService;
import com.guoliang.service.exceptionHandler.MyException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author leo
 * @since 2023-01-18
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    EduVideoService eduVideoService;
    @Override
    public List<ChapterVo> getChapterAndVideo(String id) {
        //获取课程的章节信息
        QueryWrapper<EduChapter> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",id);
        List<EduChapter> eduChapters = baseMapper.selectList(wrapper);
        //获取课程所有的小节信息
        QueryWrapper<EduVideo> wrapper1=new QueryWrapper<>();
        wrapper1.eq("course_id",id);
        List<EduVideo> eduVideos = eduVideoService.list(wrapper1);
        //封装信息
        List<ChapterVo> finalChapter=new ArrayList<>();
        for (EduChapter chapter:eduChapters) {
            ChapterVo chapterVo=new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            List<VideoVo> videoVos=new ArrayList<>();
            for (EduVideo eduvideo : eduVideos) {
                if (eduvideo.getChapterId().equals(chapter.getId())){
                    VideoVo videoVo=new VideoVo();
                    BeanUtils.copyProperties(eduvideo,videoVo);
                    videoVos.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVos);
            finalChapter.add(chapterVo);
        }
        return finalChapter;
    }

    @Override
    public boolean deleteChapter(String id) {
        //查询章节下是否存在小结 如果存在则不能删除章节
        QueryWrapper<EduVideo> wrapper=new QueryWrapper<>();
        wrapper.eq("chapter_id",id);
        long count = eduVideoService.count(wrapper);
        if (count>0){
            throw new MyException(20001,"章节下存在小节，不能删除");
        }else {
            int i = baseMapper.deleteById(id);
            return i>0;
        }
    }

    @Override
    public void removeChapterByCourseId(String id) {
        QueryWrapper<EduChapter> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",id);
        baseMapper.delete(wrapper);
    }
}
